package org.visitor.visitorserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.visitor.visitorserver.dto.FormatResponse;
import org.visitor.visitorserver.entity.User;
import org.visitor.visitorserver.mapper.UserMapper;
import org.visitor.visitorserver.service.UserServiceInter;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserServiceInter userServiceInter;

    @Autowired
    private FormatResponse formatResponse;

    @GetMapping("/selectAll")
    public FormatResponse selectAllUser() {
        try {
            List<User> li = userMapper.selectList(null);
            formatResponse.setData(li);
            formatResponse.setSuccess(true);
            formatResponse.setCode(200);
        } catch (Exception e) {
            formatResponse.setSuccess(false);
            formatResponse.setCode(400);
            formatResponse.setMsg(e.getMessage());
        }
        return formatResponse;
    }

    @PostMapping("/selectById")
    public FormatResponse getOneUser(@RequestBody Map<String, String> requestBody) {
        try {
            String id = requestBody.get("id");
            User user = userMapper.selectById(id);
            formatResponse.setData(user);
            formatResponse.setSuccess(true);
            formatResponse.setCode(200);
        } catch (Exception e) {
            formatResponse.setSuccess(false);
            formatResponse.setCode(400);
            formatResponse.setMsg(e.getMessage());
        }
        return formatResponse;
    }

    @PostMapping("/insert")
    public FormatResponse insertOneUser(@RequestBody Map<String, String> requestBody) {
        try {
            userServiceInter.insertOneUser(requestBody);
            formatResponse.setSuccess(true);
            formatResponse.setCode(200);
            formatResponse.setMsg("ok");
        } catch (Exception e) {
            formatResponse.setSuccess(false);
            formatResponse.setCode(400);
            formatResponse.setMsg(e.getMessage());
        }
        return formatResponse;
    }

    @PostMapping("/updateById")
    public FormatResponse updateOneProfessor(@RequestBody Map<String, String> requestBody) {
        try {
            userServiceInter.updateOneUser(requestBody);
            formatResponse.setSuccess(true);
            formatResponse.setCode(200);
            formatResponse.setMsg("ok");
        } catch (Exception e) {
            formatResponse.setSuccess(false);
            formatResponse.setCode(400);
            formatResponse.setMsg(e.getMessage());
        }
        return formatResponse;
    }
}
